#!/bin/bash

alias findcode='find -type f -name "*.[h,C,c,F]*" |xargs grep '
function val() { if [[ $# -ge 2 ]]; then ctrlFile=${2}; else ctrlFile=Copper.ctrl; fi; sed -n "/^${1}/p" ${ctrlFile} | cut -d "=" -f 2 | sed 's/ //g';}
function changeVal() { if [[ $# -ge 3 ]]; then ctrlFile=$3; else ctrlFile=Copper.ctrl; fi; sed -i "/^${1}/c${1} = ${2}" ${ctrlFile}; }


function val() { 
if [[ $# -ge 2 ]]; then 
    ctrlFile=${2}; 
else 
    ctrlFile=Copper.ctrl; 
fi; 
    sed -n "/^${1}/p" ${ctrlFile} | cut -d "=" -f 2 | sed 's/ //g';
}

# Stitch the data files
function stitch () {
    dirs=`ls -tr | grep "res\."`
    if [ -z "$dirs" ]; then return 0; fi;

    mkdir data -p > /dev/null 2>&1;
    if [[ ! -f data/input.tgz ]]; then
        ls *.ctrl *.data *.tab fm*.dat *.log *.gd *.plt *.yaml *.inf *.h5 2> /dev/null | xargs tar -zcvf input.tgz;
        \mv input.tgz data
    fi

    freq="";
    freqm="";
    outfile="";
    deletData=1;
    newHPC="" #deprecated
    increaseNum=0
    ARGS=`getopt -o hf:m:o:n:i:d --long fre:,freq:,fm:,freqm:,out:,new:,increse:,del -n 'example.sh' -- "$@"`
    if [ $? != 0 ]; then echo "Terminating..."; return 1; fi
    eval set -- "${ARGS}"

    while true
    do
    #    echo "first $1, second is $2"
    case "$1" in
        -h)
            echo "No help message for you!"
            return 1;
            shift
            ;;
        -f|--fre|--freq)
            freq=$2
            shift 2
            ;;
        -m|--fm|--freqm)
            freqm=$2
            shift 2
            ;;
        -o|--out)
            outfile=$2
            shift 2
            ;;
        -n|--new)
            newHPC=1
            pcid=$2
            shift 2
            ;;
        -i|--increase)
            increaseNum=$2
            shift 2
            ;;
        -d|--del)
            deletData=2;
            shift
            ;;
         --)
            shift
            break
            ;;
         *)
            echo "Internal erro!! $1"
            return 1;
            ;;
        esac
    done

    rm data/ss-[0-9][0-9]*.plt > /dev/null 2>&1;
    ii=-1;
    let ii=${ii}+${increaseNum}
    for dir in ${dirs}; do
        let ii=${ii}+1
        file=`find $dir -type f -name "stress_Total*"`
        if [[ ${ii} -eq "0" ]]; then 
            if [[ `find $dir -type f -name "*.plt"` != "" ]]; then
                \cp ${dir}/*.plt data/ ; 
            fi
        fi
        if [ -z "$file" ]; then 
            tecFiles=`find $dir -type f -name "tecdata*plt" -o -name "tecmesh*plt"`;
            if [[ "${tecFiles}" != "" && ! -f data/relax.tgz ]]; then
                tar -zcvf data/relax.tgz $tecFiles;
                rm $tecFiles
            fi
            continue; 
        else
            if [[ -f "${dir}/data.h5" ]]; then
                mv ${dir}/data.h5 data/data-${ii}.h5
            fi
        fi;
    done;

    files=`find res.* -type f -name "stress_Total*"`;
    if [ -z "$files" ]; then return; fi

    ii=0;
    let ii=${ii}+${increaseNum}
    for file in `echo "${files}" | xargs ls -tr`; do
        let ii=${ii}+1
        if [[ $ii -eq 0 ]]; then var=`cat $file | grep "="`; if [[ -z $var ]]; then continue; fi; fi;
        if [[ ${newHPC} == "" ]]; then
            newName=`printf "ss-%03d.plt" ${ii}`
        else
            newName=`printf "ss-${pcid}%02d.plt" ${ii}`
        fi
        \cp $file data/$newName -f 
    done

    if [[ $freq == "" ]]; then files=`find $dirs -type f -name "tecdata*.plt"`; else files=`find res.* -type f -name "tecdata${freq}.plt"`; fi;
    if [ ! -z "$files" ]; then
    for file in `ls -tr $files`; do
        \mv $file `echo data/${file##*/}`
    done;
    fi
 
    if [[ $freqm == "" ]]; then files=`find $dirs -type f -name "tecmesh*.plt"`; else files=`find res.* -type f -name "tecmesh${freqm}.plt"`; fi;
    if [[ ! -z "$files" ]]; then
    for file in `ls -tr $files`; do
        \mv $file `echo data/${file##*/}` -f
    done;
    fi
    
    if [[ $freqm == "" ]]; then files=`find $dirs -type f -name "gnd*.plt"`; else files=`find res.* -type f -name "gnd${freqm}.plt"`; fi;
    if [[ ! -z "$files" ]]; then
    for file in `ls -tr $files`; do
        \mv $file `echo data/${file##*/}` -f
    done;
    fi

    finalFiles=`find res.* -type f -name "tecdata.finish.plt"`
    if [ ! -z "$finalFiles" ]; then 
        finalFile=`echo "${finalFiles}" | sort | tail -n 1`
        \mv $finalFile data/tecdata.finish.plt
    fi
    finalFiles=`find res.* -type f -name "tecmesh.finish.plt"`
    if [ ! -z "$finalFiles" ]; then 
        finalFile=`echo "${finalFiles}" | sort | tail -n 1`
        \mv $finalFile data/tecmesh.finish.plt
    fi
    
    if [[ $deletData -ge 1 ]]; then
        dirs=`ls -t | grep "res"`
        rsFile="";
        for DD in ${dirs}; do
            rsFiles=`(find $DD -type f -name "rs[0-9][0-9][0-9][0-9]" && find $DD -type f -name "restart.cn")`
            if [[ -z ${rsFiles} ]] ; then continue; fi
            rsFile=`ls -t ${rsFiles} | head -n 1`
            break;
        done;
        echo "rsFile=$rsFile"
        if [[ $rsFile != "" ]]; then
            DD=`dirname ${rsFile}`
            rsfile=`echo ${rsFile##*/}`
            rscn=`echo ${rsfile} | cut -d "." -f 1`
            \cp $DD/$rscn* data/ ;
        else
            tar -zcvf data.tgz data
            echo "Warning: no restart Files"
        fi
        if [[ $deletData -ge 2 ]]; then 
            tar -zcvf data.tgz data
        fi
    fi

    return 0;
}

function ConvertDataFormat(){
    input=""; output="";

    ARGS=`getopt -o hi:o: --long help,input:,output: -- "$@"`
    eval set -- "${ARGS}"
    while true
    do
        #    echo "first $1, second is $2"
        case "$1" in
            -h|--help)
                echo ""
                shift;;
            -i|--input)
                input=$2
                shift 2;;
            -o|--output)
                output=$2;
                shift 2;;
            --)
            shift
            break
            ;;
            *)
            echo "Internal erro!! $1"
            return 1;
            ;;
        esac
    done
    echo "input=$input, output=$output"
}

function CleanEnvVariables(){

	for p in $@; do 
		patern=$(echo $p | sed "s#/#\\\/#g")
		tmp1=$(echo ${PATH} | sed "s/:/\n/g" | sed "/${patern}/d" | sed "s/$/:/g")
		tmp2=$(echo $tmp1 | sed "s/: /:/g" | sed "s/:\$//g")	
		export PATH=${tmp2}

		tmp1=$(echo ${LD_LIBRARY_PATH} | sed "s/:/\n/g" | sed "/${patern}/d" | sed "s/$/:/g")
		tmp2=$(echo $tmp1 | sed "s/: /:/g" | sed "s/:\$//g")	
		export LD_LIBRARY_PATH=${tmp2}

		tmp1=$(echo ${LIBRARY_PATH} | sed "s/:/\n/g" | sed "/${patern}/d" | sed "s/$/:/g")
		tmp2=$(echo $tmp1 | sed "s/: /:/g" | sed "s/:\$//g")	
		export LIBRARY_PATH=${tmp2}
	done
}
